package com.highcom.coffeeshop.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.highcom.coffeeshop.dao.CoffeeRepository;
import com.highcom.coffeeshop.model.Coffee;
import com.highcom.coffeeshop.model.Order;
import com.highcom.coffeeshop.model.OrderItem;

import java.util.Collections;
import java.util.List;

@Service
public class CoffeeServiceImpl implements CoffeeService {

    private final CoffeeRepository coffeeRepository;

    @Autowired
    public CoffeeServiceImpl(CoffeeRepository coffeeRepository) {
        this.coffeeRepository = coffeeRepository;
    }

    @Override
    public List<Coffee> getAllCoffees() {
        return coffeeRepository.findAll();
    }

    @Override
    public Coffee getCoffeeById(int id) {
        return coffeeRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Coffee not found with id: " + id));
    }

    @Override
    public Order createOrder(String customerName, int coffeeId, int quantity) {
        if (quantity <= 0) {
            throw new IllegalArgumentException("Quantity must be greater than 0");
        }

        Coffee coffee = getCoffeeById(coffeeId);
        OrderItem orderItem = new OrderItem(coffee, quantity);
        double totalPrice = orderItem.getSubtotal();

        return new Order(customerName, Collections.singletonList(orderItem), totalPrice);
    }
}
